package hw3.proxy.core;

import hw3.exception.StdErrReporterException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * This class is responsible for parsing dates from HTTP messages.
 *  
 * @author Adam Levi
 * @author Marina Skarbovsky
 *
 */
public class HttpDateParser
{

	private HttpDateParser()
	{
		
	}
	
	/**
	 * Tries to parse the given string to an object of type Date. 
	 * @param expirationEntry a string representing a date
	 * @param reportError a boolean that indicates if an error should be reported (
	 * in case an error exists)
	 * @return an object of type Date in case of success, otherwise null.
	 */
	public static Date getExpirationTime(String expirationEntry, boolean reportError)
	{
		if (expirationEntry == null)
		{
			return null;
		}
		SimpleDateFormat formmatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'",Locale.ENGLISH);
		try { return formmatter.parse(expirationEntry); }
		catch (ParseException e) {}
		formmatter.applyPattern("EEEEEE, dd-MMM-yy HH:mm:ss 'GMT'");
		try { return formmatter.parse(expirationEntry); }
		catch (ParseException e) {}
		formmatter.applyPattern("EEE MMM d HH:mm:ss yyyy");
		try { return formmatter.parse(expirationEntry); }
		catch (ParseException e) {}
		formmatter.applyPattern("EEE MMM dd HH:mm:ss yyyy");
		try { return formmatter.parse(expirationEntry); }
		catch (ParseException e) {}
		try // if the expiration value is a number, then we assume that the expiration date is missing
		{
			Double.parseDouble(expirationEntry);
			return null;
		}
		catch(Exception e) { /* not a number */ }
		
		if (reportError)
		{
			// write to error: unable to parse string
			StdErrReporterException.reportError(
					ResourceManager.class.getName(),
					"unable to parse to a date the given string:" + expirationEntry);	
		}
		return null;
	}
	
	/**
	 * Tests if the given date expired.
	 * @param expirationDate an object of type Date.
	 * @return true if and only if expirationDate already passed
	 */
	static boolean isDatePassed(Date expirationDate)
	{
		Date curDateTime = new Date();
		return expirationDate.before(curDateTime);
	}
}
